package com.sangeng.ss.service.impl;

import com.sangeng.ss.config.RedisCache;
import com.sangeng.ss.domain.LoginUser;
import com.sangeng.ss.domain.ResponseResult;
import com.sangeng.ss.domain.User;
import com.sangeng.ss.service.LoginService;
import com.sangeng.ss.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author ：xxx
 * @description：TODO
 * @date ：2024/02/28 14:53
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {

        // 1、封装参数完成认证
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);

        // 2、获取认证结果,存入redis
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        redisCache.setCacheObject("sys:user:" + loginUser.getUser().getId(),loginUser);

        // 3、生成jwt令牌并返回
        String jwt = JwtUtil.createJWT(loginUser.getUser().getId().toString());

        return new ResponseResult(200,"登录成功",new HashMap<String,String>(){{
            put("token",jwt);
        }});
    }

    @Override
    public ResponseResult logOut() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        redisCache.deleteObject("sys:user:" + user.getId());

        return new ResponseResult(200,"退出成功");
    }
}
